package cisdi.mes.sm.rm.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cisdi.mes.sm.rm.dao.MeasureDocDao;
import cisdi.mes.sm.rm.dao.QualDetDao;
import cisdi.mes.sm.rm.domain.SmRmMeasureDoc;
import cisdi.mes.sm.rm.domain.SmRmQualityElement;
import cisdi.mes.sm.rm.service.QualityMgr;
import cisdi.mes.sm.util.base.Arith;
import cisdi.mes.sm.util.dao.ISapDao;

@Service
public class QualityMgrImpl implements QualityMgr{

	@Autowired
	private MeasureDocDao measureDocDao;
	
	@Autowired
	private QualDetDao qualDetDao;
	
	@Autowired
	private ISapDao sapDao;
	
	public ISapDao getSapDao() {
		return sapDao;
	}

	public void setSapDao(ISapDao sapDao) {
		this.sapDao = sapDao;
	}

	public QualDetDao getQualDetDao() {
		return qualDetDao;
	}

	public void setQualDetDao(QualDetDao qualDetDao) {
		this.qualDetDao = qualDetDao;
	}

	@Override
	public Map<String, Object> decideAna(String qualityBatch) {
		Map<String, Object> map = new HashMap<String, Object>();

		String validString = validDecideAna(qualityBatch);
		if (validString.equals("success")) {
			SmRmMeasureDoc measureDoc = measureDocDao.getByQualityBatch(qualityBatch);
			measureDoc.setAnaDecide("Y");
			measureDocDao.update(measureDoc);
			List<SmRmQualityElement> anaList = qualDetDao.getAna(qualityBatch);
			sapDao.sendMatAna(anaList);
			map.put("success", true);
			map.put("message", "成分决策成功!");
		} else {
			map.put("success", false);
			map.put("message", validString);
		}

		return map;
	}

	private String validDecideAna(String qualityBatch) {
		String validString = "";

		Boolean isNotDecided = false;
		SmRmMeasureDoc measureDoc = measureDocDao.getByQualityBatch(qualityBatch);
		if (measureDoc.getAnaDecide().equals("N")) {
			isNotDecided = true;
		} else {
			validString += "*该质检批已做过成分决策<br>";
		}

		// 质检批有成分
		Boolean existAna = false;
		List<SmRmQualityElement> anaList = qualDetDao.getAna(qualityBatch);
		if (anaList != null && anaList.size() > 0) {
			existAna = true;
		} else {
			validString += "该质检批没有成分<br>";
		}

		// 质检批成分和验证[95,100]
		Boolean isAnaRight = false;
		if (existAna) {
			Double totalVal = 0d;
			for (SmRmQualityElement ana : anaList) {
				totalVal = Arith.add(totalVal, ana.getQualItemVal());
			}
			if (totalVal >= 95 && totalVal <= 100) {
				isAnaRight = true;
			}else{
				validString += "该质检批成分和" + totalVal.toString() + ",不在[95,100]区间内<br>";
			}
		}

		if (isNotDecided && existAna && isAnaRight) {
			validString = "success";
		}

		return validString;
	}

	public MeasureDocDao getMeasureDocDao() {
		return measureDocDao;
	}

	public void setMeasureDocDao(MeasureDocDao measureDocDao) {
		this.measureDocDao = measureDocDao;
	}
}
